<template>
  <div class="favorite-file-list">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>

    <!-- 空状态 -->
    <div v-else-if="files.length === 0" class="empty-container">
      <el-empty :description="t('favorites.files.emptyState')">
        <el-button type="primary" @click="handleGoToFiles">
          {{ t('favorites.files.goToFiles') }}
        </el-button>
      </el-empty>
    </div>

    <!-- 列表视图 -->
    <div v-else-if="viewMode === 'list'" class="list-view">
      <el-table
        :data="files"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column :label="t('favorites.files.fileName')" min-width="300">
          <template #default="{ row }">
            <div class="file-info">
              <div class="file-icon">
                <el-icon :size="24">
                  <component :is="getFileIcon(row.fileInfo?.mimeType, row.itemType === 'folder')" />
                </el-icon>
              </div>
              <div class="file-details">
                <div class="file-name">{{ row.fileInfo?.originalName }}</div>
                <div class="file-meta">
                  {{ formatFileSize(row.fileInfo?.fileSize) }} • 
                  {{ formatDate(row.fileInfo?.updatedAt) }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column :label="t('favorites.files.category')" width="120">
          <template #default="{ row }">
            <el-tag size="small" :type="getCategoryType(row.category)">
              {{ getCategoryLabel(row.category) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column :label="t('favorites.files.notes')" min-width="200">
          <template #default="{ row }">
            <div class="notes-text">{{ row.notes || '-' }}</div>
          </template>
        </el-table-column>

        <el-table-column :label="t('favorites.files.favoriteTime')" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>

        <el-table-column :label="t('favorites.files.actions')" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button 
                type="primary" 
                size="small" 
                :icon="View"
                @click.stop="handlePreview(row)"
              >
                {{ t('favorites.files.preview') }}
              </el-button>
              <el-button
                type="success"
                size="small"
                :icon="Download"
                @click.stop="handleDownload(row)"
              >
                {{ t('favorites.files.download') }}
              </el-button>
              <el-dropdown @command="(command: string) => handleAction(command, row)">
                <el-button size="small" :icon="More" />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="edit">
                      <el-icon><Edit /></el-icon>
                      {{ t('favorites.files.editNotes') }}
                    </el-dropdown-item>


                    <el-dropdown-item divided command="remove">
                      <el-icon><Delete /></el-icon>
                      {{ t('favorites.files.removeFavorite') }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 网格视图 -->
    <div v-else class="grid-view">
      <div class="file-grid">
        <div
          v-for="file in files"
          :key="file.id"
          class="file-card"
        >
          <div class="card-header">
            <el-checkbox 
              v-model="selectedFiles"
              :label="file.id"
              @click.stop
            />
            <el-dropdown @command="(command: string) => handleAction(command, file)">
              <el-button size="small" :icon="More" text @click.stop />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="edit">编辑备注</el-dropdown-item>


                  <el-dropdown-item divided command="remove">取消收藏</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>

          <div class="card-content">
            <div class="file-thumbnail">
              <el-icon :size="48">
                <component :is="getFileIcon(file.fileInfo?.mimeType, file.itemType === 'folder')" />
              </el-icon>
            </div>
            <div class="file-info">
              <div class="file-notes" v-if="file.notes">
                <div class="notes-content">{{ file.notes }}</div>
              </div>
              <div class="file-name" :title="file.fileInfo?.originalName">
                {{ file.fileInfo?.originalName }}
              </div>
              <div class="file-meta">
                {{ formatFileSize(file.fileInfo?.fileSize) }}
              </div>
              <div class="file-category">
                <el-tag size="small" :type="getCategoryType(file.category)">
                  {{ getCategoryLabel(file.category) }}
                </el-tag>
              </div>
            </div>
          </div>

          <div class="card-footer">
            <div class="favorite-time">
              {{ formatDate(file.createdAt) }}
            </div>
            <div class="action-buttons">
              <el-button 
                type="primary" 
                size="small" 
                :icon="View"
                @click.stop="handlePreview(file)"
              />
              <el-button 
                type="success" 
                size="small" 
                :icon="Download"
                @click.stop="handleDownload(file)"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container" v-if="files.length > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, h } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import {
  View, Download, More, Edit, Delete
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatFileSize, formatDate, getFileIcon } from '@/utils/file'

// Props
interface Props {
  files: any[]
  loading: boolean
  viewMode: 'list' | 'grid'
  total?: number
}

const props = withDefaults(defineProps<Props>(), {
  total: 0
})

// 国际化
const { t } = useI18n()

// Emits
const emit = defineEmits<{
  'remove': [file: any]
  'update': [file: any, data: any]
  'page-change': [page: number, size: number]
  'refresh': []
}>()

const router = useRouter()

// 响应式数据
const selectedFiles = ref<number[]>([])
const currentPage = ref(1)
const pageSize = ref(20)

// 计算属性
const total = computed(() => props.total)

// 事件处理
const handleSelectionChange = (selection: any[]) => {
  selectedFiles.value = selection.map(item => item.id)
}



const handlePreview = (file: any) => {
  // 跳转到文件所在文件夹并高亮文件
  console.log('🔍 预览文件，跳转到文件所在位置:', {
    fileName: file.fileInfo?.originalName,
    fileId: file.fileId,
    parentId: file.fileInfo?.parentId
  })

  const targetQuery = {
    parentId: file.fileInfo?.parentId || '0',
    highlightFile: file.fileId.toString()
  }

  console.log('🔍 跳转参数:', targetQuery)

  router.push({
    path: '/dashboard/files',
    query: targetQuery
  })
}

const handleDownload = (file: any) => {
  // TODO: 实现文件下载
  console.log('Download file:', file)
  ElMessage.info('下载功能开发中...')
}

const handleAction = async (command: string, file: any) => {
  switch (command) {
    case 'edit':
      await handleEditNotes(file)
      break
    case 'remove':
      await handleRemoveFavorite(file)
      break
  }
}

const handleEditNotes = async (file: any) => {
  try {
    const { value: notes } = await ElMessageBox.prompt(
      '请输入备注信息',
      '编辑备注',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: file.notes || '',
        inputType: 'textarea'
      }
    )
    
    emit('update', file, { notes })
  } catch (error) {
    // 用户取消
  }
}





const handleRemoveFavorite = async (file: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消收藏文件"${file.fileInfo?.originalName}"吗？`,
      '取消收藏',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    emit('remove', file)
  } catch (error) {
    // 用户取消
  }
}

const handleGoToFiles = () => {
  router.push('/dashboard/files')
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  emit('page-change', currentPage.value, size)
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  emit('page-change', page, pageSize.value)
}

// 工具函数
const getCategoryType = (category: string) => {
  const typeMap: Record<string, string> = {
    document: 'primary',
    image: 'success',
    video: 'warning',
    audio: 'info',
    archive: 'danger',
    code: 'primary',
    spreadsheet: 'success',
    presentation: 'warning',
    other: '',
    default: ''
  }
  return typeMap[category] || ''
}

const getCategoryLabel = (category: string) => {
  const labelMap: Record<string, string> = {
    document: '文档',
    image: '图片',
    video: '视频',
    audio: '音频',
    archive: '压缩包',
    code: '代码',
    spreadsheet: '表格',
    presentation: '演示文稿',
    other: '其他',
    default: '默认'
  }
  return labelMap[category] || category
}
</script>

<style scoped>
.favorite-file-list {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.loading-container {
  padding: 20px;
}

.empty-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.list-view {
  flex: 1;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.file-icon {
  flex-shrink: 0;
}

.file-details {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-weight: 500;
  color: var(--el-text-color-primary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-meta {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 2px;
}

.notes-text {
  color: var(--el-text-color-regular);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.action-buttons {
  display: flex;
  gap: 4px;
}

.grid-view {
  flex: 1;
}

.file-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  padding: 8px;
}

.file-card {
  border: 1px solid var(--el-border-color);
  border-radius: 8px;
  padding: 16px;
  background: var(--el-bg-color);
  cursor: pointer;
  transition: all 0.2s;
  min-height: 200px;
  display: flex;
  flex-direction: column;
}

.file-card:hover {
  border-color: var(--el-color-primary);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.card-content {
  text-align: center;
  margin-bottom: 12px;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.file-thumbnail {
  margin-bottom: 8px;
  color: var(--el-color-primary);
}

.file-name {
  font-weight: 500;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: var(--el-text-color-primary);
}

.file-category {
  margin-top: 8px;
}

.file-notes {
  margin-bottom: 8px;
  padding: 4px 6px;
  background: var(--el-color-primary-light-9);
  border: 1px solid var(--el-color-primary-light-7);
  border-radius: 4px;
  font-size: 11px;
}

.notes-content {
  color: var(--el-text-color-regular);
  line-height: 1.3;
  word-break: break-word;
  max-height: 32px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  font-style: italic;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.pagination-container {
  padding: 16px;
  border-top: 1px solid var(--el-border-color);
  background: var(--el-bg-color);
}
</style>
